package com.weisha.bledemo;

import android.util.Log;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by HelloWorld_ on 2017/1/16.
 */
public class Utils {

    /**
     * 字符串转byte数组
     * @param pwd
     * @return
     */
    public static Byte[] str2byte(String pwd) {

        List<Byte> rt = new ArrayList<>();

        char[] chars = pwd.toCharArray();

        for (char c : chars) {
            rt.add(Integer.valueOf(String.valueOf(c)).byteValue());
        }
        Byte[] rrt = new Byte[rt.size()];
        rt.toArray(rrt);
        return rrt;
    }

    /**
     * 校验码计算
     * @param data
     * @return
     */
    public static Byte verifyCode(Byte[] data) {
        Integer t = 0;
        for (Byte d : data) {
            t += d;
        }
        int rt = t % 256;
        return (byte) rt;
    }

    //java 合并两个byte数组
    public static Byte[] bytesMerger(Byte[] byte_1, Byte[] byte_2) {
        Byte[] byte_3 = new Byte[byte_1.length + byte_2.length];
        System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length);
        System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length);
        return byte_3;
    }

    /**
     * 截取数组
     * @param bytes
     * @return
     */
    public static Byte[] bytesCopy(byte[] bytes){
        Byte[] newByte = new Byte[11];
        System.arraycopy(bytes, 2, newByte, 0, 11);
        return newByte;
    }


    public static String toHexString(byte[] byteArray) {
        if (byteArray == null || byteArray.length < 1)
            throw new IllegalArgumentException(
                    "this byteArray must not be null or empty");

        final StringBuilder hexString = new StringBuilder();
        for (int i = 0; i < byteArray.length; i++) {
            if ((byteArray[i] & 0xff) < 0x10)
                hexString.append("0");
            hexString.append(Integer.toHexString(0xFF & byteArray[i]));
            hexString.append(" ");
        }
        return hexString.toString().toLowerCase();
    }

    public static String toHexString(byte data) {
        StringBuilder hexString = new StringBuilder();
        if ((data & 0xff) < 0x10)
            hexString.append("0");
        hexString.append(Integer.toHexString(0xFF & data));
        return hexString.toString().toLowerCase();
    }

    public static byte toHexByte(String data) {
        return (byte) Integer.parseInt(data, 16);
    }

    public static byte[] toHexBytes(String data) {

        if (data == null) {
            return null;
        }
        byte[] result = new byte[data.length() / 2];
        try {
            for (int i = 0; i < result.length; i++) {
                result[i] = (byte) Integer.parseInt(
                        data.substring(i * 2, i * 2 + 2), 16);
            }
        } catch (Exception e) {
            Log.e("Util", e.toString());
            return null;
        }
        return result;
    }
}
